package com.qiancheng.controller;


import com.qiancheng.pojo.Users;
import com.qiancheng.pojo.vo.UsersVo;
import com.qiancheng.service.impl.UserServiceImpl;
import com.qiancheng.utils.CommonJSONResult;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import static com.qiancheng.ErrorConfig.*;

@RestController
public class RegisterController {

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(value = "register",method ={RequestMethod.POST,RequestMethod.GET})
    public CommonJSONResult register(Users user){

        CommonJSONResult commonJSONResult = new CommonJSONResult();

        if (StringUtils.isBlank(user.getUsername())){
            commonJSONResult.setStatus(USERNAME_NOT_EMPTY_CODE);
            commonJSONResult.setMsg(USERNAME_NOT_EMPTY_MSG);
            return commonJSONResult;
        }

        if (StringUtils.isBlank(user.getPassword())){
            commonJSONResult.setStatus(PASSWORD_NOT_EMPTY_CODE);
            commonJSONResult.setMsg(PASSWORD_NOT_EMPTY_MSG);
            return commonJSONResult;
        }

        if (StringUtils.isBlank(user.getNickname())){
            commonJSONResult.setStatus(NICKNAME_NOT_EMPTY_CODE);
            commonJSONResult.setMsg(NICKNAME_NOT_EMPTY_MSG);
            return commonJSONResult;
        }


        //用户注册
        int resister = userService.resister(user);


        if (resister>0){
            Sid sid = new Sid();
            String token = sid.nextShort();
            UsersVo userVo = new UsersVo();

            BeanUtils.copyProperties(user,userVo);
            userVo.setToken(token);
            commonJSONResult.setStatus(SUCCESS);
            commonJSONResult.setMsg(SUCCESS_STR);
            commonJSONResult.setData(userVo);
            return commonJSONResult;
        } else {
            commonJSONResult.setStatus(REGISTER_ERROR_CODE);
            commonJSONResult.setMsg(REGISTER_ERROR_STR);
            return commonJSONResult;
        }


    }

}
